from django.db.models import Q
from django.core.urlresolvers import reverse

from browsertests.tests.models import Test
from browsertests.common.views import common_search
from .forms import TestSearchForm

def test_search(request):
    def filter_objects(form, result_list):
        if form.cleaned_data['type']:
            result_list = result_list.filter(type__in=form.cleaned_data['type'])

        file = form.cleaned_data['file']
        if file:
            result_list = result_list.filter(Q(file__contains=file) |
                                             Q(file2__contains=file))
        if form.cleaned_data['flag']:
            result_list = result_list.filter(flags__in=form.cleaned_data['flag'])
        if form.cleaned_data['tag']:
            result_list = result_list.filter(tags__in=form.cleaned_data['tag'])
        if form.cleaned_data['spec']:
            result_list = result_list.filter(sections__spec__in=form.cleaned_data['spec'])
        #if form.cleaned_data['section']:
        #    result_list = result_list.filter(sections__in=form.cleaned_data['section'])

        return result_list

    return common_search(request, 'tests', reverse('test-search'), TestSearchForm, Test,
                         'tests/test_search.html', filter_objects)
